package bar.dark.lee.memo;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class MemoListActivity extends SuperActivity
{
	private static final int REQUEST_SELECT = 0;
	private static final int REQUEST_INSERT = 1;
	protected static final int REQUEST_UPDATE = 2;
	
	public static final String START_YEAR = "start_year";
	public static final String START_MONTH = "start_month";
	public static final String END_YEAR = "end_year";
	public static final String END_MONTH = "end_month";
	public static final String TITLE_SELECT = "title_select";
	public static final String MEMO_SELECT = "memo_select";
	
	public static final String MEMO_DATA_ID = "memo_data_id";

	private DBSQLite sql;
	
	private View leftButton;
	private View rightButton;
	private TextView dateTextView;
	
	private ListView listView;
	
	private Button selectButton;
	
	private Button insertButton;
	
	private String startDate;
	private String endDate;
	
	private ArrayList<MemoData> list;
	
	private View resultView;
	
	private int startYear;
	private int startMonth;
	private int endYear;
	private int endMonth;
	
	private String titleSelect = "";
	private String memoSelect= "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(superContext);
		
		setContentView(R.layout.memo_list_activity);
		
		setTitle("메모목록");
		
		setFindView();
		setOnClickListener();
		
		Calendar cal = Calendar.getInstance();
		startYear = cal.get(Calendar.YEAR);
		startMonth = cal.get(Calendar.MONTH);
		endYear = cal.get(Calendar.YEAR);
		endMonth = cal.get(Calendar.MONTH);
		
		if (startMonth < 9)
		{
			startDate = startYear + "0" + (startMonth+1) + "00";
		}
		else
		{
			startDate = startYear + "" + (startMonth+1) + "00";
		}
		
		if (endMonth < 9)
		{
			endDate = endYear + "0" + (endMonth+1) + "32";
		}
		else
		{
			endDate = endYear + "" + (endMonth+1) + "32";
		}
		
		dateTextView.setText(startYear + "년 " + (startMonth+1) + "월 ~ " 
							+ endYear + "년 " + (endMonth+1) + "월");
		
		memoSelect = "";
		titleSelect = "";
		
		new ShowDialog().execute(BDUtil.asyncFlag, 0);
	}

	private void setFindView()
	{
		leftButton = findViewById(R.id.memoListDateLeftButton);
		rightButton = findViewById(R.id.memoListDateRightButton);
		dateTextView = (TextView) findViewById(R.id.memoListDateText);
		
		listView = (ListView) findViewById(R.id.memoListView);
		
		selectButton = (Button) findViewById(R.id.memoListSelectButton);
		insertButton = (Button) findViewById(R.id.memoListInsertButton);
		
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
	}
	
	private void setOnClickListener()
	{
		leftButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startLeftMonthButton();
			}
		});
		
		rightButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startRightMonthButton();
			}
		});
		
		selectButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, MemoSelectActivity.class);
				startActivityForResult(intent, REQUEST_SELECT);
			}
		});
		
		insertButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, MemoInsertActivity.class);
				startActivityForResult(intent, REQUEST_INSERT);
			}
		});
	}
	
	private void setData()
	{
		list = new ArrayList<MemoData>();
		
		String query = "";
		
		query = "SELECT * FROM memo_main WHERE " +
				"date >= " + startDate + " and " +
				"date <= " + endDate;
		
		if (!titleSelect.equals(""))
		{
			query += " and title LIKE '%" + titleSelect + "%'";
//			query += " or title LIKE '" + titleSelect + "%'";
//			query += " or title LIKE '%" + titleSelect + "'";
		}
		
		if (!memoSelect.equals(""))
		{
			query += " and memo LIKE '%" + memoSelect + "%'";
//			query += " or memo LIKE '" + memoSelect + "%'";
//			query += " or memo LIKE '%" + memoSelect + "'";
		}
		
		query += " ORDER BY date DESC;";
		
		sql.selectMapTile(superContext, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int titleIdx = c.getColumnIndex("title");
				int memoIdx = c.getColumnIndex("memo");
				int dateIdx = c.getColumnIndex("date");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					MemoData data = new MemoData();
					data.setId(c.getInt(idIdx) + "");
					data.setTitle(c.getString(titleIdx));
					data.setMemo(c.getString(memoIdx));
					data.setDate(c.getString(dateIdx));
					
					list.add(data);
					
					c.moveToNext();
				}
			}
		});
	}
	
	private void startLeftMonthButton()
	{
		if (startMonth == 0)
		{
			startYear--;
			startMonth = 11;
		}
		else
		{
			startMonth--;
		}
		
		endYear = startYear;
		endMonth = startMonth;
		
		titleSelect = "";
		memoSelect = "";
		
		BDUtil.startLeftDegrees(dateTextView).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
				if (startMonth < 9)
				{
					startDate = startYear + "0" + (startMonth+1) + "00";
				}
				else
				{
					startDate = startYear + "" + (startMonth+1) + "00";
				}
				
				if (endMonth < 9)
				{
					endDate = endYear + "0" + (endMonth+1) + "32";
				}
				else
				{
					endDate = endYear + "" + (endMonth+1) + "32";
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
		});
	}	
	
	private void startRightMonthButton()
	{
		if (endMonth == 11)
		{
			endYear++;
			endMonth = 0;
		}
		else
		{
			endMonth++;
		}
		
		startYear = endYear;
		startMonth = endMonth;
		
		titleSelect = "";
		memoSelect = "";
		
		BDUtil.startRightDegrees(dateTextView).setAnimationListener(new AnimationListener()
		{
			@Override
			public void onAnimationStart(Animation animation)
			{
			}
			
			@Override
			public void onAnimationRepeat(Animation animation)
			{
			}
			
			@Override
			public void onAnimationEnd(Animation animation)
			{
				if (startMonth < 9)
				{
					startDate = startYear + "0" + (startMonth+1) + "00";
				}
				else
				{
					startDate = startYear + "" + (startMonth+1) + "00";
				}
				
				if (endMonth < 9)
				{
					endDate = endYear + "0" + (endMonth+1) + "32";
				}
				else
				{
					endDate = endYear + "" + (endMonth+1) + "32";
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
		});
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3)
		{
			MemoData data = list.get(pos);
			
			Intent intent = new Intent(superContext, MemoUpdateActivity.class);
			intent.putExtra(MEMO_DATA_ID, data.getId());
			startActivityForResult(intent, REQUEST_UPDATE);
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if (resultCode == Activity.RESULT_OK)
		{
			if (requestCode == REQUEST_SELECT)
			{
				Calendar cal = Calendar.getInstance();
				
				startYear = data.getIntExtra(START_YEAR, cal.get(Calendar.YEAR));
				startMonth = data.getIntExtra(START_MONTH, cal.get(Calendar.MONTH));
				endYear = data.getIntExtra(END_YEAR, cal.get(Calendar.YEAR));
				endMonth = data.getIntExtra(END_MONTH, cal.get(Calendar.MONTH));
				
				titleSelect = data.getStringExtra(TITLE_SELECT);
				memoSelect = data.getStringExtra(MEMO_SELECT);
				
				if (startMonth < 9)
				{
					startDate = startYear + "0" + (startMonth+1) + "00";
				}
				else
				{
					startDate = startYear + "" + (startMonth+1) + "00";
				}
				
				if (endMonth < 9)
				{
					endDate = endYear + "0" + (endMonth+1) + "32";
				}
				else
				{
					endDate = endYear + "" + (endMonth+1) + "32";
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
			else if (requestCode == REQUEST_INSERT)
			{
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
			else if (requestCode == REQUEST_UPDATE)
			{
				new ShowDialog().execute(BDUtil.asyncFlag, 0);
			}
		}
	};
	
	private class MemoAdapter extends ArrayAdapter<MemoData>
	{
		public MemoAdapter(Context context, int textViewResourceId,
				List<MemoData> objects)
		{
			super(context, textViewResourceId, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null)
			{
				v = getLayoutInflater().inflate(R.layout.list_item_memo, null);
			}
			
			MemoData data = getItem(position);
			
			TextView tv1 = (TextView) v.findViewById(R.id.memoListItemDate);
			TextView tv2 = (TextView) v.findViewById(R.id.memoListItemTitle);
			
			tv1.setText(data.getDate());
			tv2.setText(data.getTitle());
			
			return v;
		}
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 0)
				{
					setData();
					
					return arg0[1];
				}
				
				return -1;
			}
			else
			{
				return -1;
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.showDialog(superContext, "오류", "데이터를 가져오는데 실패 하였습니다.");
			}
			else if (result == 0) 
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				if (startYear == endYear && startMonth == endMonth)
				{
					dateTextView.setText(startYear + "년 " + (startMonth+1) + "월");
				}
				else
				{
					dateTextView.setText(startYear + "년 " + (startMonth+1) + "월 ~ " 
							+ endYear + "년 " + (endMonth+1) + "월");
				}
				
				if (listView.getFooterViewsCount() > 0)
				{
					listView.removeFooterView(resultView);
				}
				
				if (list.size() < 1)
				{
					listView.addFooterView(resultView);
					listView.setFooterDividersEnabled(false);
					listView.setOnItemClickListener(null);
				}
				else
				{
					listView.setSelected(true);
					listView.setOnItemClickListener(onItemClickListener);
					listView.setFooterDividersEnabled(true);
				}
				
				MemoAdapter adapter = new MemoAdapter(superContext, 
						R.layout.list_item_memo, list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_MEMO);
		startActivity(intent);
	}
}
